#!/bin/bash

. /usr/sbin/balena-config-vars

keys=`jq -r 'select(.os != null) | select(.os.udevRules != null) | .os.udevRules | keys[] ' $CONFIG_PATH`
RELOAD_RULES=0
lscmd="ls"
base=`basename $0`

if [ ! -z "$keys" ]; then
	echo "$base: Found custom udev rules in $CONFIG_PATH"
	while read -r key; do
		echo "$base: Found custom udev rule: $key"
		lscmd="$lscmd -I \"$key.rules\""
		filter="'.os.udevRules.\"$key\"'"
		cmd="jq -r $filter $CONFIG_PATH"
		rule=$(eval "$cmd")
		if [ -f "/etc/udev/rules.d/$key.rules" ] && [ "$(cat "/etc/udev/rules.d/$key.rules")" = "$rule" ]; then
			echo "$base: /etc/udev/rules.d/$key.rules already exists"
			continue
		else
			RELOAD_RULES=1
			echo "$base: New rule or modified rule detected. Writing /etc/udev/rules.d/$key.rules and reloading"
			echo "$rule" > "/etc/udev/rules.d/$key.rules"
		fi
	done <<< "$keys"

	if [ ! -f /etc/udev/rules.d/README ]; then
		echo "Files here are auto-generated by balena-custom-udev-rules. Extra files will be removed" >> /etc/udev/rules.d/README
	fi

	lscmd="$lscmd /etc/udev/rules.d"
	extra_rules=$(eval "$lscmd")
	while read -r extra_rule; do
		if [ "$extra_rule" != "README" ]; then
			echo "$base: Removing extra rule: $extra_rule"
			rm "/etc/udev/rules.d/$extra_rule"
		fi
	done <<< "$extra_rules"

	if [ $RELOAD_RULES -eq 1 ]; then
		echo "Wait for udev to settle"
		sleep 60
		echo "Reloading udev rules"
		udevadm control --reload-rules
		echo "Triggering udev"
		systemctl restart systemd-udev-trigger.service
	else
		echo "$base: All rules from config.json already present. Not reloading/writing"
	fi
else
	echo "$base: No custom udev rules found in $CONFIG_PATH"
	if [ "$(ls -A /etc/udev/rules.d -I README)" ]; then
		rm /etc/udev/rules.d/* || true
	fi
fi
